<template>
  <!--广告创意-->
  <div>
    <!--广告创意-->
    <SectionContainer class="u-p20 u-pb0">
      <SectionTitle>广告创意
        <el-tooltip
          slot="tip"
          class="item"
          effect="dark"
          placement="top"
          content="数据更新时间2小时，当天数据仅供参考，请以隔天数据为准"
        >
          <i class="iconfont iconfont-10 c-hint-major"></i>
        </el-tooltip>
      </SectionTitle>

      <!-- 筛选 -->
      <el-form
        inline
        class="m-filter"
        label-position="left"
      >
        <el-row>
          <el-form-item label="投放时间：">
            <el-date-picker
              :clearable="false"
              v-model="filter.daterange"
              value-format="yyyy-MM-dd"
              size="small"
              type="daterange"
              range-separator="至"
              start-placeholder="投放开始日期"
              end-placeholder="投放结束日期"
              class="u-w300"
              :picker-options="DATERANGE_OPTIONS"
              @change="daterangeChange"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item v-show="isFilterToday">
            <el-select
              v-model="filter.particle"
              size="small"
              class="u-w145"
              filterable
              placeholder="请选择统计粒度"
            >
              <el-option
                v-for="item in DATA_AD_PARTICLE"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="数据维度：">
            <el-select
              v-model="filter.dimensionality"
              size="small"
              class="u-w145"
              filterable
              placeholder="请选择数据维度"
            >
              <el-option
                :value="0"
                label="创意维度"
              ></el-option>
              <el-option
                :value="1"
                label="广告位维度"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="投放层级：">
            <el-select
              v-model="filter.planId"
              size="small"
              class="u-w145"
              filterable
              placeholder="请选择广告计划"
              @change="planIdChange"
            >
              <el-option
                v-for="item in planOptions"
                :key="item.planId"
                :label="item.planName"
                :value="item.planId"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="filter.unitId"
              size="small"
              filterable
              class="u-w145 u-ml10"
              placeholder="请选择广告单元"
              @change="unitIdChange"
            >
              <el-option
                v-for="item in unitOptions"
                :key="item.unitId"
                :label="item.unitName"
                :value="item.unitId"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="filter.creativeId"
              size="small"
              filterable
              class="u-w145 u-ml10"
              placeholder="请选择广告创意"
            >
              <el-option
                v-for="item in creativeOptions"
                :key="item.creativeId"
                :label="item.creativeName"
                :value="item.creativeId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="filter.dimensionality === 0">
            <el-button
              @click="search"
              size="small"
              type="primary"
            >查询</el-button>
          </el-form-item>
        </el-row>
        <el-row v-if="filter.dimensionality === 1">
          <el-form-item label="投放广告：">
            <el-select
              v-model="filter.adxId"
              size="small"
              class="u-w145"
              filterable
              placeholder="请选择ADX平台"
              @change="adlocalAdxChange"
            >
              <el-option
                v-for="item in adlocalAdxOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="filter.mediaId"
              size="small"
              filterable
              class="u-w145 u-ml10"
              placeholder="请选择投放媒体"
              @change="adlocalMediaChange"
            >
              <el-option
                v-for="item in adlocalMediaOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="filter.pid"
              size="small"
              filterable
              class="u-w145 u-ml10"
              placeholder="请选择广告位名称"
            >
              <el-option
                v-for="item in adlocalSpaceOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="search"
              size="small"
              type="primary"
            >查询</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </SectionContainer>

    <!--数据报表-->
    <SectionContainer
      class="u-p20"
      v-if="isChartLine"
    >
      <SectionTitle>数据报表</SectionTitle>
      <ChartLine :data="chartOptions"></ChartLine>
    </SectionContainer>

    <!--数据明细-->
    <SectionContainer class="u-p20">
      <SectionTitle>数据明细</SectionTitle>

      <!-- 表格 -->
      <TableFull
        :data="tableData"
        :column-data="tableColumn"
        :total="tableTotal"
        :current-page="page.pageNo"
        @current-change="currentChange"
        @size-change="sizeChange"
      >
        <el-form
          inline
          class="m-filter"
          slot="handle"
        >
          <el-form-item>
            <el-button
              size="small"
              @click="exportReport"
            >导出报表</el-button>
          </el-form-item>
          <el-form-item v-permission="['data_creative_importData']">
            <el-upload
              :action="`${UPLOAD_BASE_URL}/manage/api/bus/data/uploadflie?userId=${user.userId}`"
              :headers="{'x-access-token': user.token}"
              :show-file-list="false"
              :on-success="importSuccess"
              :before-upload="importBeforeUpload"
            >
              <el-popover
                placement="top-start"
                width="400"
                trigger="hover"
              >
                <div class="u-lh24">
                  <span class="c-hint-error">注意：</span><br>
                  1、已结算日期的数据不要重复导入！<br>
                  2、今日数据导入后，会在今日结束后统一进行结算。（即今日数据不会显示在财务交易明细列表里，财务-累计消耗和余额会正常计算）
                </div>
                <el-button
                  slot="reference"
                  size="small"
                >导入数据</el-button>
              </el-popover>
            </el-upload>
          </el-form-item>
          <el-form-item v-permission="['data_creative_downloadTemplate']">
            <el-button
              size="small"
              @click="importTemplate"
            >下载模板</el-button>
          </el-form-item>
          <el-form-item v-permission="['data_creative_manualClearing']">
            <el-button
              size="small"
              @click="settlementDialogVisible = true"
            >手动结算</el-button>
          </el-form-item>
          <el-form-item>
            <CustomTableColumn
              :module="2"
              :columns.sync="tableColumn"
            />
          </el-form-item>
        </el-form>
        <template slot="column">
          <!-- eslint-disable -->
          <el-table-column
            :resizable="false"
            align="center"
            v-for="(item, index) in tableColumn"
            v-if="item.visible"
            :key="index"
            :label="item.label"
            :sort-by="item.prop"
          >
            <el-table-column
              :resizable="false"
              align="center"
              :label="item.prop === 'reportTime' ? '总计' : getTableDataSumValue(item.prop, {rate: ['bidsSuccessRate', 'clickRate', 'realClickRate', 'profitRatio']})"
              :prop="item.prop"
              :width="item.width"
              class-name="u-table--total"
            >
              <template slot-scope="scope">
                <!-- 日期 -->
                <template v-if="item.prop === 'reportTime'">
                  <span v-html="formatMultiLineTime(scope.row[item.prop])"></span>
                </template>
                <!-- 所属层级 -->
                <template v-else-if="item.prop === 'hierarchy'">
                  <div class="u-tl">{{scope.row.planName}}/{{scope.row.unitName}}</div>
                </template>
                <!-- 添加百分比号 * 100 -->
                <template v-else-if="['bidsSuccessRate', 'clickRate', 'realClickRate', 'profitRatio'].indexOf(item.prop) !== -1 && scope.row[item.prop] !== null">{{decimalMultiply(scope.row[item.prop], 100) + '%'}}</template>
                <!-- 左对齐 -->
                <template v-else-if="['creativeName'].indexOf(item.prop) !== -1">
                  <div class="u-tl">{{scope.row[item.prop]}}</div>
                </template>
                <!-- 其他 -->
                <template v-else>{{scope.row[item.prop]}}</template>
              </template>
            </el-table-column>
          </el-table-column>
        </template>
      </TableFull>
    </SectionContainer>

    <!-- 导入完成的提示 -->
    <DialogImport
      :visible.sync="importVisible"
      :fail="importData.fail"
      :success="importData.success"
      :messages="importData.messages"
    ></DialogImport>

    <!-- 手动结算 -->
    <DialogConfirm
      :visible.sync="settlementDialogVisible"
      :buttons="['确 定', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmSettlement"
      content="是否确定手动结算？"
      tip="1、导入的数据确认无误后，再点击手动结算！！<br>2、同一日期，数据只结算一次，以首次结算为准！！（即不同adx、不同创意ID，如果数据日期相同，仅可结算一次）<br>3、今日导入的数据，无论是否手动结算，系统会在今日结束后自动结算的！"
    ></DialogConfirm>
  </div>
</template>

<script>
import Moment from "moment";

import SectionContainer from "@/components/section-container";
import SectionTitle from "@/components/section-title";
import ChartLine from "@/components/chart-line";
import TableFull from "@/components/table-full";
import DialogImport from "@/components/dialog-import";
import DialogConfirm from "@/components/dialog-confirm";
import CustomTableColumn from "@/components/custom-table-column";

import { DATA_AD_PARTICLE } from "@/assets/js/common-option";
import DATERANGE_OPTIONS from "@/assets/js/daterange-option";
import { formatMultiLineTime, sessionStorage, hasPermission } from "@/utils";
import { decimalMultiply } from "@/utils/decimal";
import permissionMixin from "@/mixins/permission";
import {
  fetchAdLocalSelect,
  fetchPlanSelect,
  fetchUnitSelect,
  fetchCreativeSelect,
  fetchDataCreativeDay,
  fetchDataCreativeHour,
  fetchDataExportCreativeDay,
  fetchDataExportCreativeHour,
  fetchDataCreativeSettlement
} from "@/api";

export default {
  mixins: [permissionMixin],
  components: {
    SectionContainer,
    SectionTitle,
    ChartLine,
    TableFull,
    DialogImport,
    DialogConfirm,
    CustomTableColumn
  },
  data() {
    return {
      UPLOAD_BASE_URL: process.env.VUE_APP_UPLOAD_BASE_URL,
      user: sessionStorage.get("USER"),

      DATA_AD_PARTICLE,
      DATERANGE_OPTIONS,

      // 手动结算
      settlementDialogVisible: false,

      // 导入弹窗
      importVisible: false,
      importLoading: null,
      importData: {},

      planOptions: [],
      unitOptions: [],
      creativeOptions: [],

      // 投放广告位
      adlocalAdxOptions: [],
      adlocalMediaOptions: [],
      adlocalSpaceOptions: [],

      filter: {
        dimensionality: 0, // 数据维度
        particle: 0, // 统计粒度 0 按天，1 按小时
        daterange: [
          Moment()
            .subtract(6, "days")
            .format("YYYY-MM-DD"),
          Moment().format("YYYY-MM-DD")
        ], // 时间段
        planId: "", // 广告计划
        unitId: "",
        creativeId: "",
        adxId: "",
        mediaId: "",
        pid: ""
      },

      page: {
        pageNo: 1,
        pageSize: 50
      },

      // 表格
      tableData: [],
      tableColumn: [
        {
          label: "日期",
          prop: "reportTime",
          fixed: true,
          width: 110,
          visible: true
        },
        {
          label: "广告位名称",
          prop: "adspaceName",
          width: 150,
          visible: false
        },
        {
          label: "ADX平台",
          prop: "adxName",
          width: 80,
          visible: false
        },
        {
          label: "投放媒体",
          prop: "mediaName",
          width: 80,
          visible: false
        },
        {
          label: "创意名称",
          prop: "creativeName",
          width: 150,
          visible: true
        },
        {
          label: "创意ID",
          prop: "creativeId",
          visible: true
        },
        {
          label: "所属层级",
          prop: "hierarchy",
          width: 150,
          visible: true
        },
        {
          label: "实际出价次数",
          prop: "responseNumber",
          visible: hasPermission(["data_creative_bidsResponseNumber"])
        },
        {
          label: "实际竞价成功率",
          prop: "bidsSuccessRate",
          visible: hasPermission(["data_creative_bidsSuccessRate"])
        },
        {
          label: "曝光数",
          prop: "displayNumber",
          visible: true
        },
        {
          label: "点击数",
          prop: "clickNumber",
          visible: true
        },
        {
          label: "点击率",
          prop: "clickRate",
          visible: true
        },
        {
          label: "点击均价(元)",
          prop: "cpcAveragePrice",
          visible: true
        },
        {
          label: "千次曝光均价(元)",
          prop: "cpmAveragePrice",
          visible: true
        },
        {
          label: "APP开始下载数",
          prop: "downloadStartNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP下载完成数",
          prop: "downloadCompleteNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP开始安装数",
          prop: "installationStartNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP安装完成数",
          prop: "installationCompleteNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP激活数",
          prop: "activationNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP注册数",
          prop: "registeredNumber",
          visible: false,
          custom: true
        },
        {
          label: "总消耗(元)",
          prop: "biddingPrice",
          visible: true
        },
        {
          label: "实际曝光数",
          prop: "realDisplayNumber",
          visible: hasPermission(["data_creative_realDisplayNumber"])
        },
        {
          label: "实际点击率",
          prop: "realClickRate",
          visible: hasPermission(["data_creative_realClickRate"])
        },
        {
          label: "实际点击均价(元)",
          prop: "realCpcAveragePrice",
          visible: hasPermission(["data_creative_realCpcAveragePrice"])
        },
        {
          label: "实际千次曝光均价(元)",
          prop: "realCpmAveragePrice",
          visible: hasPermission(["data_creative_realCpmAveragePrice"])
        },
        {
          label: "实际总消耗(元)",
          prop: "realBiddingPrice",
          visible: hasPermission(["data_creative_realBiddingPrice"])
        },
        {
          label: "盈利金额(元)",
          prop: "profitAmount",
          visible: hasPermission(["data_creative_profitAmount"])
        },
        {
          label: "合计盈利比",
          prop: "profitRatio",
          visible: hasPermission(["data_creative_profitRatio"])
        }
      ],
      tableTotal: 0,

      chartOptions: {},
      isChartLine: true
    };
  },
  computed: {
    // 选择的是否今天
    isFilterToday() {
      return (
        this.filter.daterange[0] === this.filter.daterange[1] &&
        this.filter.daterange[0] === Moment().format("YYYY-MM-DD")
      );
    },
    filterBody() {
      let params = {};
      if (this.filter.dimensionality === 1) {
        params = {
          adxId: this.filter.adxId,
          mediaId: this.filter.mediaId,
          pid: this.filter.pid
        };
      }
      return {
        ...params,
        dimensionality: this.filter.dimensionality,
        startTime: this.filter.daterange[0],
        endTime: this.filter.daterange[1],
        planId: Number(this.filter.planId),
        unitId: Number(this.filter.unitId),
        creativeId: Number(this.filter.creativeId),
        particle: this.filter.particle
      };
    }
  },
  methods: {
    decimalMultiply,
    formatMultiLineTime,

    // adx改变
    adlocalAdxChange(id) {
      // 媒体
      this.filter.mediaId = "";
      this.adlocalMediaOptions = this.adlocalAdxOptions.find(
        item => item.id === id
      ).children;
      // 广告位
      this.filter.pid = "";
      this.adlocalSpaceOptions = [];
    },
    // 媒体改变
    adlocalMediaChange(id) {
      // 广告位
      this.filter.pid = "";
      this.adlocalSpaceOptions = this.adlocalMediaOptions.find(
        item => item.id === id
      ).children;
    },
    // 广告位
    fetchAdLocalSelect() {
      return fetchAdLocalSelect({
        query: {
          unionId: 0, // adx
          mediaId: 0, // 媒体
          adspaceType: 0 // 创意形式，默认
        }
      }).then(res => {
        this.adlocalAdxOptions = res.data.list;
      });
    },
    // 手动结算
    confirmSettlement(index) {
      if (index === 0) {
        this.importSettlement();
      } else {
        this.settlementDialogVisible = false;
      }
    },
    // 导出报表
    exportReport() {
      let request = [fetchDataExportCreativeDay, fetchDataExportCreativeHour][
        this.filter.particle
      ];
      request({
        query: {
          userId: this.user.userId
        },
        body: this.filterBody
      }).then(res => {
        if (res.data) {
          location.href = res.data;
        }
      });
    },
    // 导入的数据手动结算
    importSettlement() {
      fetchDataCreativeSettlement({
        query: {
          userId: this.user.userId
        }
      }).then(() => {
        this.settlementDialogVisible = false;
        this.$message.info("结算操作成功");
      });
    },
    // 导入数据
    importSuccess(res) {
      if (res.code === 0) {
        this.importVisible = true;
        this.importData = res.data;
        this.getTable();
      } else {
        this.$message({
          type: "error",
          message: res.msg
        });
      }
      this.importLoading.close();
    },
    importBeforeUpload(file) {
      const type = /\.xlsx?$/.test(file.name);
      if (!type) {
        this.$message.error("请上传excel格式的文件");
      }
      this.importLoading = this.$loading({
        lock: true,
        text: "正在导入...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      return type;
    },
    importTemplate() {
      location.href = "/xls/data-creative-template.xls";
    },
    // 广告计划下拉数据
    fetchPlanSelect() {
      fetchPlanSelect({
        query: {
          userId: this.user.userId
        }
      }).then(res => {
        this.planOptions = [
          {
            planId: "",
            planName: "全部计划"
          }
        ].concat(res.data);
      });
    },
    // 广告单元下拉数据
    fetchUnitSelect() {
      fetchUnitSelect({
        query: {
          userId: this.user.userId,
          planId: this.filter.planId
        }
      }).then(res => {
        this.unitOptions = [
          {
            unitId: "",
            unitName: "全部单元"
          }
        ].concat(res.data);
      });
    },
    // 广告创意下拉数据
    fetchCreativeSelect() {
      fetchCreativeSelect({
        query: {
          userId: this.user.userId,
          unitId: this.filter.unitId
        }
      }).then(res => {
        this.creativeOptions = [
          {
            creativeId: "",
            creativeName: "全部创意"
          }
        ].concat(res.data);
      });
    },
    // 图表数据
    getChartOptions(data) {
      let ret = {
        legend: {
          left: "70",
          selectedMode: "single"
        },
        xAxis: [],
        series: [
          {
            name: "点击数",
            data: []
          },
          {
            name: "曝光数",
            data: []
          },
          {
            name: "点击率",
            data: []
          },
          {
            name: "点击均价",
            data: []
          },
          {
            name: "千次曝光均价",
            data: []
          },
          {
            name: "总消耗",
            data: []
          }
        ]
      };
      data.forEach(item => {
        ret.xAxis.push(item.reportTime);
        [
          "clickNumber",
          "displayNumber",
          "clickRate",
          "cpcAveragePrice",
          "cpmAveragePrice",
          "biddingPrice"
        ].forEach((serie, index) => {
          ret.series[index].type = "line";
          ret.series[index].lineStyle = {
            width: 3
          };
          ret.series[index].data.push(item[serie]);
        });
      });
      return ret;
    },
    // 查询
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    // 获取表格数据
    getTable() {
      this.tableData = [];
      this.tableTotal = 0;
      this.chartOptions = {};
      this.isChartLine = false;
      let request = [fetchDataCreativeDay, fetchDataCreativeHour];
      request[this.filter.particle]({
        query: {
          userId: this.user.userId
        },
        body: {
          ...this.page,
          ...this.filterBody
        }
      }).then(res => {
        this.isChartLine = !!res.data.list.length;
        this.chartOptions = this.getChartOptions(res.data.echartsList);
        this.tableTotal = res.data.count;
        if (res.data.list && res.data.list.length) {
          this.tableData = this.modTableDataSumList(
            res.data.sumList,
            res.data.list
          );
        }
      });
    },
    // 给第一行数据添加总计相关数据
    modTableDataSumList(sumList, data) {
      let sum = sumList.length ? sumList[0] : {};
      let sumObj = {};
      for (let key in sum) {
        sumObj[`__` + key] = sum[key];
      }
      data[0] = {
        ...data[0],
        ...sumObj
      };
      return data;
    },
    // 获取总计的相关值
    getTableDataSumValue(prop, { rate }) {
      let sum = this.tableData[0] || {};
      let sumProp = `__${prop}`;
      if (sumProp in sum) {
        let value = sum[sumProp];
        // 添加百分比
        if (rate.indexOf(prop) !== -1) {
          return decimalMultiply(value, 100) + "%";
        }
        return String(value);
      }
      return "";
    },
    // 分页
    currentChange(val) {
      this.page.pageNo = val;
      this.getTable();
    },
    sizeChange(val) {
      this.page.pageSize = val;
      this.getTable();
    },
    planIdChange() {
      this.filter.unitId = "";
      this.filter.creativeId = "";
      this.fetchUnitSelect();
    },
    unitIdChange() {
      this.filter.creativeId = "";
      this.fetchCreativeSelect();
    },
    // 日期改变
    daterangeChange() {
      if (!this.isFilterToday) {
        this.filter.particle = 0;
      }
    }
  },
  watch: {
    // 广告位维度展示列
    "filter.dimensionality"(v) {
      this.tableColumn.forEach(item => {
        if (["adspaceName", "adxName", "mediaName"].includes(item.prop)) {
          item.visible = v === 1;
        }
      });
      this.getTable();
    }
  },
  created() {
    this.fetchPlanSelect();
    this.fetchUnitSelect();
    this.fetchCreativeSelect();
    this.fetchAdLocalSelect();
    this.getTable();
  }
};
</script>